var RATE = $.cookie("RingRate") || 1;
var orderID;
var app_url=location.origin;
(function(){
	var order={
		init:function(){
			//导航栏的选中
            $('.wrapper').navbarscroll();
            $("#categories li").eq(3).addClass("cur").siblings().removeClass("cur");
            this.loadOrder();
			this.BindEvents();
			this.CustomerOrderStatusNum();
		},
		BindEvents:function(){
			var self = this;
			if(APP){
				$("#product-box").remove();
				$("#OrderStatus").remove();
				$("#retr").hide();
			}else{
				$("#retr").show();
			}
			//订单状态的选中
			$("#OrderStatus span").on("click",function(){
				$(this).addClass("active").siblings().removeClass("active");
				self.loadOrder();
			});
			 //跳转页面
             $("#categories a").on("click",function(){
            	var link_url=$(this).attr("data-href");
//          	if(APP){
//          		var appJson={};
//         			appJson.title=$(this).attr("data-title");
//         			appJson.url=app_url+link_url;	
//         			console.log(JSON.stringify(appJson))
//         			YiYi_APP.showNewPage(JSON.stringify(appJson));
//          	}else{
            		location.href = link_url;
            	//}
            });
			//取消订单
            $(".order-list").on("click",'span.cancel-order-btn',function () {
            	var orderID = $(this).attr("data-id");
			    myApp.prompt('请在下面输入框说明取消原因', '取消订单', function (value) {
			    	if(value!="" && $.trim(value).length != 0){
			    		self.cancelOrder(orderID,value);
			    	}else{
			    		 myApp.alert('取消原因不能为空！');
			    	}
			    	//   @*主题色start*@
			        $(document.createElement("script")).attr("src","/Js/ThemesColor.js").appendTo("html");
					//  @*主题色end*@
			    });
            });
			//筛选
            $("#order_term_btn").on("click", function () {
                if(APP){
                	var appJson={};
            		appJson.title="订单筛选";
            		appJson.url=app_url+"/Customer/OrderFilter/?type=3";
            		YiYi_APP.showNewPage(JSON.stringify(appJson));
                }else{
                	location.href="/Customer/OrderFilter/?type=3";
                }
            });
            //切换成品类型
			$("#mainType span").on("click",function(){
				type=$("#mainType span.active").attr("data-value");
				self.changType(type);				
			});
			 //点击订单到订单详情
            $("#order").on("click",".list_detail_box",function(){
            	var orderId=$(this).attr("data-id");
            	if(APP){
            		var appJson={};
            		appJson.title="订单详情";
            		appJson.url=app_url+"/Customer/OrderDetail/?ID="+orderId+"&type=3";
            		YiYi_APP.showNewPage(JSON.stringify(appJson));
            	}else{
            		location.href="/Customer/OrderDetail/?ID="+orderId+"&type=3";
            	}
            });
             //随便逛逛
            $("#go_to_shop").on("click",function(){
            	var link_url=$(this).attr("data-href");
            	if(APP){
            		var appJson={};
					appJson.title="成品库存";
           			appJson.function_menu="goods_search";
           			appJson.goods_type="3";
           			YiYi_APP.showExistingPage(JSON.stringify(appJson));
            	}else{
            		location.href=link_url;
            	}
            });
		},
		//统计订单状态的个数
		CustomerOrderStatusNum:function(){
            var requestOrder = {};
            requestOrder.CustomerID = CustomerID; 
            requestOrder.GoodsType = 3
            $.ajax({
                url: "/Team/GetOrderNewNumber",//提交地址
                type: "POST",//提交方式
                data: JSON.stringify(requestOrder),
                contentType: "application/json; charset=utf-8",
                success: function (result) {
                    var _result = eval('(' + result + ')');//eval()解析单个json对象
                    var total = 0;
                    if(_result.msgcode== true){
                        _result=_result.msginfo;
                        for (var i = 0; i < _result.length; i++) {
                            if (_result[i].OrderStatus == 1) {
                                $("#status1").text(_result[i].Number);
                                total += _result[i].Number;
                            }
                            if (_result[i].OrderStatus == 2) {
                                $("#status2").text(_result[i].Number);//订单
                                total += _result[i].Number;
                            }
                            if (_result[i].OrderStatus == 3) {
                                $("#status3").text(_result[i].Number);//订单
                                total += _result[i].Number;
                            } 
                            if (_result[i].OrderStatus == 4) {
                                $("#status4").text(_result[i].Number);//订单
                                total += _result[i].Number;
                            } 
                            if (_result[i].OrderStatus == 5) {
                                $("#status5").text(_result[i].Number);//订单
                                total += _result[i].Number;
                            }
                            if (_result[i].OrderStatus == 6) {
                                $("#status6").text(_result[i].Number);//订单
                                total += _result[i].Number;
                            }
                            $("#status0").html(total);//订单总数
                        }
                    }else{
                        $("#status0").text(total);//订单总数
                        $("#status1").text(0);//订单
                        $("#status2").text(0);//订单
                        $("#status3").text(0);//订单
                        $("#status4").text(0);//订单
                        $("#status5").text(0);//订单
                        $("#status6").text(0);//订单
                    }
                }
            });
        },
		 //获取筛选参数
        getParameters: function () {
           if(PARAMS!=null){
				var orderParams=PARAMS.orderParams;
			}else{
				var orderParams={};
				orderParams.CustomerID = CustomerID;//客户ID
	            orderParams.PageSize = 100;
	            orderParams.PageIndex = 1;
	            orderParams.OrderStatus=0;
			}
			if(!APP){
				orderParams.OrderStatus=$("#OrderStatus span.active").attr("data-value");				
			}
			return orderParams;
        },
		//加载订单
        loadOrder: function () {
            var self = this;
            myApp.showIndicator();//显示加载中
            var p = self.getParameters();//获取参数
            p.GoodsType=3;
            //获取排序
            var sort = $(".filter-box li i[data-sort-direct]");//获取排序框
            if (p && sort.length > 0 && sort.attr("data-sort-direct")) {//参数和排序长度均大于0,且存在data-sort-direct属性
                p["SortColumn"] = sort.attr("data-sort");//获取排序名称，退点或总价
                p["SortDirect"] = sort.attr("data-sort-direct");//获取排序类型，升序或降序
            }
            var requestJson = JSON.stringify(p);
            
            $.ajax({
                url: "/Team/GetOrderNewList",
                type: "POST",
                data: requestJson,
                contentType: "application/json",
                timeout: 30000, //超时时间：30秒
                success: function (result) {
                    self.BindingOrder(result);//绑定数据
                    myApp.hideIndicator();//隐藏加载中
                    if(APP){
		        		YiYi_APP.refreshOrderNumber();//重新统计状态数量
		        	}
                },
	            error: function(XMLHttpRequest, textStatus, errorThrown){
					myApp.hideIndicator();//隐藏加载中
					myApp.alert("网络超时，请重试");
				},
            });
        },
        //绑定数据
        BindingOrder: function (result) {
        	
            var _result = eval('(' + result + ')');//eval()解析单个json对象
            if (_result.msgcode == false) {//获取库存失败
                $(".null-cart-tip").show();
                $("#order .order-list").hide();
                $("#total_num").text(0);
                $("#total_usd").text(0);
                $("#total_rmb").text(0);
            } else { //获取库存成功
                $(".null-cart-tip").hide();
                $("#order .order-list").show();
                $("#total_num").text(_result.msginfo.TotalCount);
                _result = _result.msginfo;
                var lis = "";//多行数据
                var total_rmb=0;
				var total_usd=0;
                for (var i = 0; i < _result.length ; i++) {//_result.length
					var li = ""; //单行
                    var data = _result[i];
                    var data_parse=JSON.parse(data.InventoryAttribute)
					var otherPar = "";
					var otherPar1 = "";
					var otherPar2 = "";
					var otherPar3 = "";
					
					if(data_parse.Category!=1){
						otherPar +="<b>"+GetText("inlays",data_parse.Category,data_parse.MainColor,"MainColor")+"</b>"+
						"<b>"+data_parse.MainCertNo+"</b><b>"+data_parse.MainCertType+"</b>";
					}
					if(data_parse.Category==2||data_parse.Category==3){
					    otherPar1 += "<b>" + GetText("inlays", data_parse.Category, data_parse.MainClarity, "MainClarity") + "</b>";
					}
					if(data_parse.Category==4||data_parse.Category==5){
					    otherPar2 += "<b>" + GetText("inlays", data_parse.Category, data_parse.Process, "Process") + "</b>";
					}
					if(data_parse.Category>3){
					    otherPar3 += "<b>" + GetText("inlays", data_parse.Category, data_parse.Place, "Place") + "</b>";
					}

					//订单权限start
					var materialOrderPower='';
                         materialOrderPower= "<b>" + GetText("inlays", data_parse.Category,data_parse.Material ,"Material")+ "</b>"
                    var weightOrderPower='';
                        weightOrderPower="<b>重" + data_parse.Weight + "g</b>"

                    var priceOrderPower='';
                    if(RMBRingPrice_td_new==true){
                         priceOrderPower= "<span class='CurrentRMB'>￥<b class='product_list_price'>" + formatRMBPrice(data.ConfirmRMB) +"</b></span>";
                    }
                    if(priceRing_td_new==true){
                        priceOrderPower+= "<span class='CurrentUSD'>$<b class='product_list_price'>" + formatUSDPrice(data.ConfirmUSD) +"</b></span>";
                    }
                    //订单权限end

                    lis += "<li><div class='product_list'>"+
                    "<label style='display:none'></label>"+
                    "<div class='list_img_box'>"+ShowImgOne(data_parse)+"</div>"+
					"<div class='list_detail_box' data-id="+data.OrderID+">"+
					"<p id='spec_list'>"+
					"<b>" + GetCategory("inlays", data_parse.Category) + "</b><b style='float:left'>货号" + data_parse.OriginSN + "</b>" +
                    "<b>" + GetText("inlays", data_parse.Category, data_parse.Type, "Type") + "</b><b>" + GetText("inlays", data_parse.Category, data_parse.Style, "Style") + "</b>" +
                    // "<b>" + GetText("inlays", data_parse.Category,data_parse.Material ,"Material")+ "</b>"+
                        materialOrderPower+
                    "<b>" + GetText("inlays", data_parse.Category, data_parse.Country, "Country") + "</b><b>" + data_parse.Measurement + "</b>" +weightOrderPower+
                    "<b>" + data_parse.Series + "</b>"+otherPar+otherPar1+otherPar2+otherPar3+
                        // "<b>"+GetText("inlays",data_parse.Category,data_parse.MainShape,"MainShape") +"</b>"
                        // (GetText("inlays",data_parse.Category,data_parse.MainShape,"MainShape")) +
                    "</p>"+
					"<div class='list_price'>"+priceOrderPower+
					"<span class='status_box' lang='"+data.OrderStatus+"'>"+CustomerOrderStatusFormat(data.OrderStatus)+"</span></div>"+
					"<div class='time_box'>下单日期：<span class='order-time'>"+DateTimeFormat(data.CreateTime)+"</span></div>"+
					"</div></div>"+modify_cancel(data)+
					"</li>";
					total_rmb+=Number(formatRMBPrice(data.ConfirmRMB));
					total_usd+=Number(formatUSDPrice(data.ConfirmUSD));
					lis += li;//将单行加到多行
                }
                $("#order .order-list ol").html(lis);//加入到id为inventory的figures中
                currentShow();  //币种设置
                //统计
                $("#total_usd").text(formatUSDPrice(total_usd));
                $("#total_rmb").text(formatRMBPrice(total_rmb));
                //   @*主题色start*@
                $(document.createElement("script")).attr("src","/Js/ThemesColor.js").appendTo("html");
				//  @*主题色end*@
            }
        },
        
        //确定取消订单
        cancelOrder: function (orderID,remarks) {
            var self = this;
            var result = {};
            if(orderID){
            	result.OrderIDs = orderID;
            }else{
            	result.OrderIDs = $("#orderId").html();
            }
            result.GoodsType=3;
            result.Remarks = remarks;
                $("#remarks").css("border-color", "#d5d5d5");
                $.ajax({
                    url: "/Team/CancelOrdersNew",//提交地址
                    type: "POST",//提交方式
                    data: JSON.stringify(result),
                    contentType: "application/json; charset=utf-8",
                    timeout: 30000, //超时时间：30秒
                    success: function (result) {
                        var _result = eval('(' + result + ')');//eval()解析单个json对象

                        myApp.alert(_result["msginfo"],function(){
                        	self.loadOrder();//加载订单列表
                        });                       
                    },
		            error: function(XMLHttpRequest, textStatus, errorThrown){
						myApp.alert("网络超时，请重试");
					},
                });
        },
        
	}
	order.init();
})();

function modify_cancel(data){
	var status = data.OrderStatus;
	if(status == 1){
		return "<div class='btn_box'><a href='paymentPage'></a><span class='order_btn cancel-order-btn' data-id='"+data.OrderID+"'>取消订单</span></div>";
	}else{
		return "";
	}
}